/**
 * Copyright (c) 2019, ShangHai YTO Co., Ltd.
 * All right reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF YTO
 * CO., LTD.  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED
 * TO THIRD PARTIES, COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 * WITHOUT THE PRIOR WRITTEN PERMISSION OF YTO
 * CO., LTD.
 */
package org.sc.xl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;

/**
 * @description: TODO 请在此添加描述
 * @reason: TODO ADD REASON(可选)
 * @author FXL
 *
 * @date 2024/4/16 9:11 
 * @since JDK 1.8
 */
public class StampLockTest {

    private static int x = 0, y = 0;

    private static StampedLock stampedLock = new StampedLock();


    public static void main(String[] args) {



        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int j = 0; j < 20; j++) {
//            executorService.submit(() -> read());
        }
        for (int i = 0; i < 10; i++) {
            int finalI = i;
//            executorService.submit(() -> move(finalI, finalI));
        }

        for (int j = 0; j < 20; j++) {
//            executorService.submit(() -> read());
        }

        executorService.shutdown();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDateTime =  LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endDateTime = startDateTime.plusDays(8).withHour(0).withMinute(0).withSecond(0);
        System.err.println(formatter.format(startDateTime));
        System.err.println(formatter.format(endDateTime));
    }

    private static void move(int deltaX, int deltaY) {
        long stamp = stampedLock.writeLock();
        try {
            x += deltaX;
            y += deltaY;
            System.err.println("当前线程所携带编号: " + deltaX + " (x=" + x + " y=" + y + ")" + " 当前锁stamp变量:" + stamp);
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }


    private static void read() {
        long stamp = stampedLock.tryOptimisticRead();
        System.out.println("尝试开始获取读锁,stamp变量:" + stamp);
        if (!stampedLock.validate(stamp)) {
            long lock = stampedLock.readLock();
            try {
                System.out.println("当前线程ID:" + Thread.currentThread().getId() + " 线程名称:" + Thread.currentThread().getName() + " 当前 x=" + x + " , y=" + y);
            } finally {
                stampedLock.unlockRead(lock);
            }
        }
    }
}